package com.example.test003.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.UnsupportedEncodingException;

@RestController
public class DownloadController {

    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> downloadFile() {
        // 加载本地的 Word 文档
        File file = new File("C:\\Users\\Cold'Rain\\Desktop\\操作说明.docx");
        FileSystemResource resource = new FileSystemResource(file);

        // 构建响应头
        HttpHeaders headers = new HttpHeaders();
        String fileName = "操作说明.docx";
        String encodedFileName = null;
        try {
            encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + encodedFileName);
        System.out.println("下载操作说明");
        // 返回文件内容作为响应
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}